package com.example.library_demo.controller;


import cn.hutool.core.util.RandomUtil;
import com.example.library_demo.annotation.Auth;
import com.example.library_demo.common.Result;
import com.example.library_demo.entity.Card;
import com.example.library_demo.entity.User;
import com.example.library_demo.enums.GlobalResponseResultEnum;
import com.example.library_demo.common.Result;
import com.example.library_demo.service.ICardService;
import com.example.library_demo.service.IUserService;
import com.example.library_demo.vo.card.CardVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Eric
 * @since 2024-11-28
 */
@RestController
@RequestMapping("/card")
public class CardController extends BaseController {

    @Autowired
    private ICardService cardService;
    @Autowired
    private IUserService userService;

    @Auth
    @GetMapping("/num/{cardNum}")
    public Result<CardVO> getCardByCardNumber(@PathVariable String cardNum){
        CardVO card = cardService.getCardByCardNumber(cardNum);
        if(null == card){
            return Result.error(GlobalResponseResultEnum.HANDEL_FAIL.getCode(),
                    "Can not find any card like ["+cardNum+"],please check again.");
        }
        return Result.success(card);
    }

    @Auth
    @GetMapping("/user/{userId}")
    public Result<List<CardVO>> getCardByCardNumber(@PathVariable Long userId){
        List<CardVO> rst = cardService.getCardByUserId(userId);
        return Result.success(rst);
    }

    @Auth
    @PostMapping
    public Result<CardVO> add(){
        User user = super.getCurrentUser();
        Card card = new Card();
        String defaultStr = "" + LocalDate.now().getYear() + LocalDate.now().getMonthValue() + LocalDate.now().getDayOfMonth();
        String cardNum=defaultStr + RandomUtil.randomNumbers(5);
        while(true){
            cardNum = defaultStr + RandomUtil.randomNumbers(5);
            if(!cardService.checkIsExistByCardNum(cardNum)){
                break;
            }
        }
        card.setCardNum(cardNum);
        card.setBalance(new BigDecimal(0));
        card.setUserId(user.getUserId());
        cardService.save(card);
        CardVO vo = new CardVO();
        BeanUtils.copyProperties(card,vo);
        return Result.success(vo);
    }

    @Auth
    @GetMapping("/my")
    public Result<List<CardVO>> myCardDetail(){
        User user = super.getCurrentUser();
        List<CardVO> rst = cardService.getCardByUserId(user.getUserId());
        return Result.success(rst);
    }
}

